<?php

class Default_IndexController extends Common_Controller_Front {

    /**
     *
     * @var Zend_Session_Namespace
     */
    private $session = null;

    public function init() {
        parent::init();

        $this->session = $this->view->session = new Zend_Session_Namespace('index', true);
    }

    public function indexAction() {
        
    }

    public function msgAction() {
        
    }

    public function jsongetAction() {
        $this->noOut();
        $this->postOff = true;

        if ($this->_request->isXmlHttpRequest() && $this->_request->isPost()) {

            $table = $this->getParam('m', false);
            $model = self::MODEL_PREFIX . ucfirst($table);
            $inst = new $model();

            $item = $inst->{$this->getParam('f', 'getById')}($this->getParam('id'));

            echo $this->json(array(
                'status' => 'ok',
                'result' => $this->getParam('id'),
                'row' => is_object($item) ? $item->toArray() : $item
            ));
        }
    }

    public function contentAction() {

        $id = $this->getParam('id', 0);
        $contents = new Application_Model_Content();
        $content = $contents->getById($id);

        $this->view->displayContentOff = 1;
       
        
        if ($content) {

            $matches = array();
            preg_match_all('#\{([^\}]+)\}#', $content->body, $matches);

            foreach ($matches[1] as $match) {
                if (defined($match)) {
                    $content->body = preg_replace('#\{' . $match . '\}#', constant($match), $content->body);
                }
            }

            $this->view->content = $content;
        } else {

            $this->getResponse()->setHttpResponseCode(404);
            $this->render('404');
        }
    }

    public function categoryAction() {

        $id = $this->getParam('id', 0);
        $categories = new Application_Model_Categories();
        $content = new Application_Model_Content();

        $category = $categories->getById((int) $id);

        $this->view->displayContentOff = 1;

        $brd = $categories->getToHome((int) $id);


        foreach ($brd as $idx => $item) {
            $item['link'] = $this->view->url(
                    array(
                'module' => 'default',
                'controller' => 'index',
                'action' => 'category',
                'id' => $item['id'],
                    ), null, true
            );
            $item['label'] = $item['title'];
            $brd[$idx] = $item;
        }



        $brd[] = array(
            'label' => 'Home',
            'link' => '/',
        );



        $this->view->brd = array_reverse($brd);

        //var_dump($this->view->brd);

        $paginator = $this->getPaginator(
                $content->getAdapterPaginForCategories(
                        'categoryId IN (' . join(',', array_values($categories->getToHome((int) $id, 'id'))) . ')'
                )
        );

        if ($category) {
            $this->view->category = $category;
        } else {

            $this->getResponse()->setHttpResponseCode(404);
            $this->render('404');
        }

        $this->view->paginator = $paginator;
    }

    public function addAction() {
        $this->noOut();


        $id = $this->getParam('id', false);

        if ($id) {
            $adds = new Application_Model_Content();
            $add = $adds->getById($id);

            if (!empty($add) && array_search($add->typ, array(Application_Model_Content::TYP_ADD, Application_Model_Content::TYP_EXTADD)) !== false) {


                $stats = new Application_Model_Contentstat();
                if ($this->addsSession->{'addId' . $add->id}) {
                    $stats->insert(array(
                        'itemId' => $add->id,
                        'created' => date("Y-m-d H:i:s", time()),
                        'type' => Application_Model_Contentstat::T_ADDCLICK,
                        'userId' => $this->getLoggedUserId(),
                    ));
                }
                $this->addsSession->{'addId' . $add->id} = $add;

                $this->redirect(empty($add->addUrl) ? $_SERVER['HTTP_REFERER'] : $add->addUrl);
            }
        }
    }

    public function taskAction() {

        $taskModel = new Application_Model_Tasks();
        $code = $this->getParam('code', 0);
        $id = $this->getParam('id', 0);

        $task = $taskModel->getById($id);


        if (isset($task) && !empty($task)) {

            if ($task->status == Application_Model_Tasks::S_WTOKU) {

                $nm = Common_Cron_Executor::_CEXEC_PREFIX . ucfirst($task->class);
                try {
                    $exec = new $nm($this);

                    if (method_exists($exec, 'completeTask')) {
                        $exec->completeTask($task);
                    }
                } catch (Exception $e) {
                    var_dump($e);
                    exit;
                }
            }
        }
    }

}

